package com.cocolover2.andbase;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cocolover2.andbase.utils.BugFixUtil;
import com.cocolover2.andbase.utils.FileUtil;

import java.io.File;
import java.lang.reflect.Field;

/**
 * webview轻量级的封装<br>
 * 1.支持图片上传<br>
 * 2.支持js<br>
 * 3.支持缩放<br>
 * 4.支持拨号<br>
 * 5.支持下载功能<br>
 * Created by liubo on 7/11/16.
 */
public class AndWebBaseActivity extends AndBaseActivity implements DownloadListener {

    public static final int FILECHOOSER_RESULTCODE = 0xff;

    protected WebView mWebView;
    protected ValueCallback mValueCallback;//文件选择，针对4.1

    /**
     * 初始化webview的配置
     *
     * @param webviewId webview的id
     */
    public void initWebView(int webviewId) {
        mWebView = (WebView) findViewById(webviewId);
        initWebSettings(mWebView);
        mWebView.setWebViewClient(new CustomWebClient());
        mWebView.setWebChromeClient(new CustomWebChromeClient());
        //设置超链接下载功能
        mWebView.setDownloadListener(this);
        mWebView.requestFocus();
    }

    @SuppressWarnings("all")
    protected void initWebSettings(WebView webView) {
        WebSettings webSettings = webView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);

        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setLoadsImagesAutomatically(true);
        //开启DOM缓存
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCachePath(getCacheDir().getPath());
        webSettings.setAllowFileAccess(true);
        //支持js
        webSettings.setJavaScriptEnabled(true);
    }

    /**
     * 调用web端的javascript方法
     *
     * @param methodName 方法名
     * @param json       参数以json字符串形式传递
     */
    public void invokeJavaScriptMethod(final String methodName, final String json) {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:" + methodName + "('" + json + "')");
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    protected void handleUrlLoading(WebView view, String url) {
        if (url.startsWith("tel:")) {//拨号
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);
        } else {
            view.loadUrl(url);
        }
    }

    @SuppressWarnings("all")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mValueCallback)
                return;
            Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
            if (result == null) {
                mValueCallback.onReceiveValue(null);
                mValueCallback = null;
                return;
            }
            Log.i("UPFILE", "onActivityResult" + result.toString());
            String path = FileUtil.getPathByUri(this, result);
            if (TextUtils.isEmpty(path)) {
                mValueCallback.onReceiveValue(null);
                mValueCallback = null;
                return;
            }
            Uri uri = Uri.fromFile(new File(path));
            Log.i("UPFILE", "onActivityResult after parser uri:" + uri.toString());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mValueCallback.onReceiveValue(new Uri[]{uri});
            } else {
                mValueCallback.onReceiveValue(uri);
            }
            mValueCallback = null;
        }
    }

    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
        //这里使用第三方浏览器执行文件下载功能
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }


    private class CustomWebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            handleUrlLoading(view, url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }


    private class CustomWebChromeClient extends WebChromeClient {
        //当WebView进度改变时更新窗口进度
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //Activity的进度范围在0到10000之间,所以这里要乘以100
            onProgressChanging(view, newProgress);
        }

        //5.0以上调用
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            mValueCallback = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            return true;
        }

        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mValueCallback = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
            i.setType(type);
            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        /*网上主流的那些设置webview为空之类的方式，只是在部分机型可以解决。
最简单的解决方式就是给按钮给足够的时间，即使是界面已经销毁了。
也就是延迟销毁webview*/
        if (mWebView != null) {
            mWebView.getSettings().setBuiltInZoomControls(true);
            mWebView.setVisibility(View.GONE);
            long timeout = ViewConfiguration.getZoomControlsTimeout();//timeout ==3000
            mWebView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mWebView.removeAllViews();
                    mWebView.destroy();
                    setConfigCallback(null);
                }
            }, timeout);
        }
    }

    public void setConfigCallback(WindowManager windowManager) {
        try {
            Field field = WebView.class.getDeclaredField("mWebViewCore");
            field = field.getType().getDeclaredField("mBrowserFrame");
            field = field.getType().getDeclaredField("sConfigCallback");
            field.setAccessible(true);
            Object configCallback = field.get(null);

            if (null == configCallback) {
                return;
            }

            field = field.getType().getDeclaredField("mWindowManager");
            field.setAccessible(true);
            field.set(configCallback, windowManager);
        } catch (Exception e) {
        }
    }

    /**
     * 显示网页加载进度
     *
     * @param view webview实例
     * @param newProgress 范围0~10000
     */
    public void onProgressChanging(WebView view, int newProgress) {

    }


}
